﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HuangCanAPI.CustomAttribute
{
    /// <summary>
    /// MVC授权过滤器
    /// </summary>
    public class MVCAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 判断用户是否有权访问
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns>如果授权满足要求，返回ture，反之返回false</returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {

            // 如果访问的是登录页面，则返回true
            // 得到当前的这次请求，Controller和Action
            // 获得请求的Controller
            var controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
            // 获得请求的Action
            var actionName = HttpContext.Current.Request.RequestContext.RouteData.Values["Action"].ToString();
            // 白名单
            if (controllerName.ToLower() == "home" && actionName.ToLower() == "login")
            {
                return true;
            }
            if (httpContext.Session["username"] == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 如果用户不满足授权要求，如何返回数据
        /// </summary>
        /// <param name="filterContext"></param>

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new ContentResult() { Content = "请重新登录" };
        }



    }
}